const {Server} = require("socket.io")
const handle = require("./handle");

class Socket {
    constructor(server) {
        this.io = new Server(server, {})

        this.io.on('connect', (socket) => {
            if (socket?.handshake?.auth?.token !== '123456') {
                socket.emit('unConnect', '密钥不符' + socket?.handshake?.auth?.token)
                return socket.disconnect()
            }

            socket.on('disconnect', () => {
                console.log(`${socket.id} 离线！`)
            })

            socket.on('getList', async (params) => {
                try {
                    let res = await handle.getList(params)
                    console.log(res)
                    socket.emit('getList', res)
                } catch (e) {
                    console.log(e)
                    socket.emit('getList', e)
                }


            })
            socket.on("disconnecting", (reason) => {
                for (const room of socket.rooms) {
                    if (room !== socket.id) {
                        socket.to(room).emit("user has left", socket.id);
                    }
                }
            });
            socket.on('close', function (event) {
                socket.disconnect()
            })
        })
    }
}

module.exports = Socket

